package com.doublefish.doublefishrobot.base;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.doublefish.doublefishrobot.R;


/**
 * 作者:dugaofeng on 2025/3/10 08:42
 *
 * 做一个service 用于后台播放MP3，保活
 */
public class DFService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        playMp3();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 创建通知渠道（API 26及以上）
        NotificationChannel channel = new NotificationChannel("my_service", "My Background Service", NotificationManager.IMPORTANCE_HIGH);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(channel);

        // 创建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "my_service")
                .setContentTitle(getString(R.string.super_5_robot_2))
                .setContentText(getString(R.string.sending_code_tips))
                .setSmallIcon(R.mipmap.icon); // 使用你的图标资源

        startForeground(9876, builder.build()); // 开始前台服务
        return START_STICKY; // 如果服务被杀死，系统会尝试重新创建服务
    }

    @Override
    public void onDestroy() {
        pauseMp3();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private MediaPlayer mediaPlayer;
    private void playMp3() {
        if (mediaPlayer == null) {
//            mediaPlayer = MediaPlayer.create(this, R.raw.a2);
            //部分机型不能播放无声音乐 ，只能用有声音乐
            mediaPlayer = MediaPlayer.create(this, R.raw.a3);
            mediaPlayer.setLooping(true);
        }
        if (mediaPlayer.isPlaying()) {
            return;
        }
        mediaPlayer.start();
    }

    private void pauseMp3() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }
}
